'use strict';

const Controller = require('egg').Controller;

const jwt = require('jsonwebtoken');

class UserController extends Controller {
    //注册
    async registry() {
        let {ctx,service} = this;
        //获取前端传递的参数
        let {username,password} = ctx.request.body;
        //容错处理
        if(username && /\d{4,6}/.test(password)){
            //1.排重
            let target = await service.user.selectUser(username);
            if(target.length){
                //已经注册
                ctx.body = {
                    code:3,
                    msg:'已注册'
                }
            }else{
                //密码加密
                let hmcPwd = ctx.helper.hmc(password);
                try{
                    await service.user.registry(username,hmcPwd);
                    ctx.body = {
                        code:1,
                        msg:'注册成功'
                    }
                }catch(e){
                    ctx.body = {
                        code:0,
                        msg:e
                    }
                }
            }   
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //登录
    async login(){
        let {ctx,service} = this;
        let {username,password} = ctx.request.body;
        if(username && /\d{4,6}/.test(password)){
            //密码
            let hmcPwd = ctx.helper.hmc(password);
            let target = await service.user.login(username,hmcPwd);
            console.log(target);
            if(target.length){
               //生成token，进京证
                //jwt.sign(签入的内容,秘钥,{过期时间})
                let token = jwt.sign({username,role_id:target[0].role_id},'1801a',{expiresIn:60*60*5});
                ctx.body ={ 
                    code:1,
                    msg:'登录成功',
                    token
                }
            }else{
                ctx.body ={ 
                    code:0,
                    msg:'登录失败'
                }
            }
        }else{
            ctx.body = {
                code:0,
                msg:'参数有误'
            }
        }
    }
}

module.exports = UserController;
